package CollectionTest.Homework;

import java.util.*;

/*
3.分别用Comparable和Comparator两个接口对下列四位同学的成绩做降序排序，如果成绩一样，
那在成绩排序的基础上按照年龄由小到大排序。
姓名（String）年龄（int）分数（float）
liusan			20				90.0F
lisi			22				90.0F
wangwu			20				99.0F
sunliu			22				100.0F
编写一个Student类用来实现Comparable<Student>接口,并在其中重写CompareTo(Student o)方法　
在主函数中使用Comparable 与 Comparetor分别对ArrayList进行排序.
 */
public class Test3 {
    public static void main(String[] args){
        List<Student> studentList = new ArrayList<Student>();
        Student s1 = new Student("刘三",20,90.0F);
        Student s2 = new Student("李四",22,90.0F);
        Student s3 = new Student("王五",20,99.0F);
        Student s4 = new Student("孙六",22,100.0F);
        studentList.add(s1);
        studentList.add(s2);
        studentList.add(s3);
        studentList.add(s4);
        //实现Comparable接口
        //Collections.sort(studentList);

        //自定义比较规则 实现Comparator接口
        Collections.sort(studentList,new StudentComparator());
        //遍历集合
        Iterator<Student> it = studentList.iterator();
        while(it.hasNext()){
            Student s = it.next();
            System.out.println(s);
        }
    }
}
class Student implements Comparable<Student>{
    private String name;
    private int age;
    private float score;

    public Student() {
    }

    public Student(String name, int age, float score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public float getScore() {
        return score;
    }

    public void setScore(float score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "姓名:"+this.name+" 年龄:"+this.age+" 分数"+this.score;
    }
    //编写排序规则
    public int compareTo(Student s){
        if(this.score == s.score){
            return this.age - s.age;
        }else{
            return Float.compare(s.score,this.score);
        }
    }
}


class StudentComparator implements Comparator<Student> {

    //编写排序规则
    public int compare(Student s1, Student s2){
        if(s1.getScore() == s2.getScore()){
            return s1.getAge() - s2.getAge();
        }else{
            return Float.compare(s2.getScore(), s1.getScore());
        }
    }
}
